import axios from 'axios';
import qs from 'qs';
import config from '../config/index'
import router from '../router'
import { ElMessage } from 'element-plus'

const TOKEN_INVALID = 'Token认证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常，请稍后重试'

const instance = axios.create({
    baseURL: '/api',
    timeout: 10000,
    headers: { "authorization": "Bearer " + localStorage.getItem('token') }
});

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么

    const headers = config.headers;
    if (!headers.Authorization) headers.Authorization = 'Bearer ';

    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 对响应数据做点什么

    const { status, data, msg } = response.data;
    if (status === 200) {
        return data;
    } else if (status === 401) {
        ElMessage.error(TOKEN_INVALID)
        setTimeout(() => {
            router.push('/login')
        }, 1500)
        return Promise.reject(TOKEN_INVALID)
    } else {
        ElMessage.error(msg || NETWORK_ERROR)
        return Promise.reject(msg || NETWORK_ERROR)
    }

    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

function request(options) {
    // console.log(options);
    // console.log(instance.defaults);
    options.method = options.method || 'get'
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data;
    }
    let isMock = config.mock;
    if (typeof options.mock != 'undefined') {
        isMock = options.mock;
    }
    if (config.env === 'production') {
        instance.defaults.baseURL = config.baseApi
    } else {
        instance.defaults.baseURL = isMock ? config.mockApi : config.baseApi
    }

    return instance(options)
}


export default request